﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Xml;
using System.Windows.Forms;
using Javavaj.iHunter;
using Javavaj.iHunter.Core;

namespace Javavaj.iHunter.RssChannels
{
    public class RssChannelFactory : IChannelFactory
    {

        private IList<KeyValuePair<string, string>> rsslist = null; // <title, uri>
        private XmlDocument settings = null;

        public RssChannelFactory()
        {
            rsslist = new List<KeyValuePair<string, string>>();
        }

        #region IChannelFactory Members

        public IEnumerable<IChannel> ListChannels()
        {
            foreach (KeyValuePair<string, string> pair in rsslist)
            {
                yield return new RssChannel(pair.Key, pair.Value);
            }
            yield break;
        }

        #endregion

        #region IPlugin Members

        public void InitSettings(XmlDocument sts)
        {
            /* The Xml setting document looks like this:
             * <Settings>
             *     <Channel>
             *         <Chosen>True/False</Chosen>
             *         <Title>xxx</Title>
             *         <Uri>xxx</Uri>
             *     </Channel>
             *     <Channel>
             *         <Chosen>True/False</Chosen>
             *         <Title>xxx</Title>
             *         <Uri>xxx</Uri>
             *     </Channel>
             * <Settings>
             */

            rsslist.Clear();
            settings = sts;

            try
            {
                foreach (XmlElement ele in settings.DocumentElement.GetElementsByTagName("Channel"))
                {
                    if (bool.Parse(ele["Chosen"].InnerText) == true)
                        rsslist.Add(new KeyValuePair<string, string>(ele["Title"].InnerText, ele["Uri"].InnerText));
                }
            }
            catch
            {
                //MessageBox.Show("插件配置错误。请重新设置。", "RSS");
                rsslist.Clear();
            }
            return;
        }

        public void Config()
        {
            ConfigDialog cd = new ConfigDialog(settings);
            cd.ShowDialog();
            if (cd.DialogResult == DialogResult.OK)
            {
                settings = cd.NewSettings;
                this.InitSettings(settings);
                if (SettingChanged != null)
                    SettingChanged.Invoke(this, new PluginSettingChangedEventArgs(this, settings));
            }
            cd.Close();
        }

        public event PluginSettingChangedEventHandler SettingChanged;

        #endregion
    }
}
